package main

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/whxnhk/simple-go-routing/route"
)

func main() {
	// 使用示例
	mux := route.NewMux()

	// 直接添加路由
	mux.AddRoute(&route.Route{
		Pattern: "/hello",
		Memo:    "hello测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "hello测试")
		},
	})

	// 创建路由组
	group := route.NewRouteGroup("/say", "say测试", nil)
	// 添加路由到群组
	group.Add(&route.Route{
		Pattern: "", // 默认/say未被占用，只做分组标识，此处不会产生冲突
		Memo:    "hello首页测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "say index")
		},
	})
	group.Add(&route.Route{
		Pattern: "/hello",
		Memo:    "hello测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "say hello")
		},
	})
	// 添加到mux
	mux.AddRouteGroup(group)

	// mux直接创建group，已自动添加到mux
	group1 := mux.CreateRouteGroup("/run", "run测试")
	group1.Add(&route.Route{
		Pattern: "/hi",
		Memo:    "hi测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "run hi")
		},
	})
	// 添加路由也会自动绑定到mux
	group1.Add(&route.Route{
		Pattern: "/hello",
		Memo:    "hello测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "run hello")
		},
	})

	// 用接口添加
	mux.AddIRoute(&Demo{})
	mux.AddIRouteGroup(&Demo{}) // group拼接后是 /demo/...与上面不冲突

	// 叠加绑定
	group.Add((&Demo{}).Route())
	group.AddGroup((&Demo{}).RouteGroup())

	// 显示所有路由
	mux.ShowRouteMap()

	// 设置鉴权
	mux.SetAuthFunc(func(w *http.ResponseWriter, r *http.Request) bool {
		cookie, err := r.Cookie("token")
		if err == nil {
			if cookie.Value == "123" {
				return true
			}
		}
		if r.URL.Query().Get("pw") != "123" {
			return false
		}
		http.SetCookie(*w, &http.Cookie{
			Name:    "token",
			Value:   "123",
			Expires: time.Now().Add(24 * time.Hour),
			Path:    "/",
		})
		return true
	})

	mux.AddFileDir("/f/", "./", "测试静态文件f")
	// 启动服务
	mux.Serve(":6543")
}

type Demo struct{}

func (d *Demo) Route() *route.Route {
	return &route.Route{
		Pattern: "/demo_route",
		Memo:    "demo_route测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "demo_route测试")
		},
	}
}

func (d *Demo) RouteGroup() *route.RouteGroup {
	group := route.NewRouteGroup("/demo", "demo group测试", nil)
	group.Add(&route.Route{
		Pattern: "/index",
		Memo:    "demo首页测试",
		Func: func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprint(w, "index page")
		},
	})
	return group
}
